package com.qqserver.service;

import com.qqcommon.Message;
import com.qqcommon.MessageType;
import com.qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;

public class ServerConnectClientThread extends Thread{
    private Socket socket = null;
    private String userId;//连接到服务端的Id

    public ServerConnectClientThread(Socket socket,String userId) {
        this.socket = socket;
        this.userId = userId;
    }

    public Socket getSocket() {
        return socket;
    }

    @Override
    public void run(){
        while (true){
            System.out.println("服务端和客户端"+userId+"保持通信，读取数据.....");
            try {
                Message message = null;
                /**
                 * 存在bug处理离线问题时，当有多条留言时只显示第一条
                 */
                //处理未收消息，存在bug处理离线问题时
                if (StoreMessage.getMessage(userId) != null){
                    message = StoreMessage.getMessage(userId);
                    StoreMessage.removeMessage(userId);
                }else {
                    //读取客户端消息
                    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    //接收客户端发送的消息对象
                    message = (Message) ois.readObject();
                }
                //为什么不用switch语句,switch语句用return
                //如果读取到的服务端返回的用户在线列表信息
                if (message.getMesType().equals(MessageType.MESSAGE_GET_ONLINE_FRIEND)){
                    System.out.println(message.getSender()+"要在线用户列表");
                    String onlineUser = ManageServerConnectClientThread.getOnlineUser();
                    //返回Message
                    Message message2 = new Message();
                    //设置Message返回的content值
                    message2.setContent(onlineUser);
                    message2.setMesType(MessageType.MESSAGE_RET_ONLINE_FRIEND);
                    message2.setGetter(message.getSender());//接收者
                    //发送给客户端
                    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                    oos.writeObject(message2);
                }
                //群发
                else if (message.getMesType().equals(MessageType.MESSAGE_TO_ALL_MES)){
                    System.out.println(message.getSender()+"向在线用户发送消息");
                    HashMap<String,ServerConnectClientThread> hashMap = ManageServerConnectClientThread.getHm();
                    //迭代器遍历
                    Iterator<String> iterator = hashMap.keySet().iterator();
                    while (iterator.hasNext()){
                        //在线用户
                        String onlineUserId = iterator.next();
                        if (!onlineUserId.equals(message.getSender())){
                            ObjectOutputStream oos = new ObjectOutputStream
                                    (hashMap.get(onlineUserId).getSocket().getOutputStream());
                            oos.writeObject(message);
                        }
                    }
                }
                //文件类型
                else if (message.getMesType().equals(MessageType.MESSAGE_FILE_MES)){
                    System.out.println(message.getSender()+"向"+message.getGetter()+"用户发送文件");
                    //接收者Thread
                    ServerConnectClientThread senderThread = ManageServerConnectClientThread.getServerConnectClientThread(message.getGetter());
                    //在线情况下
                    if (senderThread != null){
                        ObjectOutputStream oos = new ObjectOutputStream(senderThread.getSocket().getOutputStream());
                        oos.writeObject(message);
                    }
                    //离线情况下
                    else {
                        StoreMessage.addMessage(message.getGetter(),message);
                        System.out.println("用户不在线，暂存");
                        break;
                    }
                }
                //私聊
                else if (message.getMesType().equals(MessageType.MESSAGE_COMM_MES)){
                    System.out.println(message.getSender()+"用户向"+message.getGetter()+"用户发送消息");
                    //接收者Thread
                    ServerConnectClientThread senderThread = ManageServerConnectClientThread.getServerConnectClientThread(message.getGetter());
                    //在线情况下
                    if (senderThread != null){
                        ObjectOutputStream oos = new ObjectOutputStream(senderThread.getSocket().getOutputStream());
                        oos.writeObject(message);
                    }
                    //离线情况下
                    else {
                        StoreMessage.addMessage(message.getGetter(),message);
                        System.out.println("用户不在线，暂存");
                        break;
                    }

                }
                //退出
                else if (message.getMesType().equals(MessageType.MESSAGE_CLIENT_EXIT)){
                    System.out.println(message.getSender()+"用户退出");
                    //移除线程
                    ManageServerConnectClientThread.removeServerConnectClientThread(message.getSender());
                    //关闭线程
                    socket.close();
                    //退出循环
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
